package com.presto.directo.utils

import okhttp3.ConnectionPool
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.*

object RetrofitMap {

    val map = mutableMapOf<RetrofitKey, Retrofit>()

    fun getRetrofit(baseUrl: String, time: Long = 10L): Retrofit {
        val retrofitKey = RetrofitKey(baseUrl, time)
        var retrofit = map[retrofitKey]
        if (retrofit == null) {
            val okHttpClient = OkHttpClient.Builder()
                .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .connectTimeout(time, TimeUnit.SECONDS)
                .readTimeout(time, TimeUnit.SECONDS)
                .writeTimeout(time, TimeUnit.SECONDS)
                .connectionPool(ConnectionPool(15, 10, TimeUnit.MINUTES))
                .build()
            retrofit = Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create(GsonUtil.getInstance())) //请求的结果转为实体类
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create()) //适配RxJava2.0
                .baseUrl(baseUrl)
                .build()
            map[retrofitKey] = retrofit
        }
        return retrofit!!
    }

}


data class RetrofitKey(
    val baseUrl: String = "",
    val time: Long = 10L
)